package com.yang.minioBackend.controller;

import com.yang.minioBackend.config.MinIOInfo;
import com.yang.minioBackend.entity.UserInfo;
import com.yang.minioBackend.result.R;
import com.yang.minioBackend.service.UserContractService;
import com.yang.minioBackend.service.UserImageService;
import com.yang.minioBackend.service.UserInfoService;
import io.minio.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;

    @Resource
    private UserImageService userImageService;

    @Resource
    private UserContractService userContractService;

    @Resource
    private MinioClient minioClient;

    @Resource
    private MinIOInfo minIOInfo;

    @GetMapping(value = "/api/users")
    public R users(){
        List<UserInfo> list = userInfoService.list();
        return R.OK(list);
    }

    /**
     * 上传图片
     */
    @PostMapping(value = "/api/user/image")
    public R uploadImage(MultipartFile file, @RequestParam(value = "id") Long id) throws Exception {
        //例如 1234.jpg 获取文件类型 jpg
        // file.getOriginalFilename().indexOf(".") 原始文件名中查找第一个出现的 . 的位置
        // file.getOriginalFilename().substring(...) 从文件名中提取从索引 4 开始到结尾的所有字符，即从第一个.后开始的所有字符。
        String subFix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        String object = id+subFix;

        // 上传图片到 MinIO
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder()
                .bucket(minIOInfo.getBucket()) // 配置桶名称
                .object(object) //设置对象名
                .stream(file.getInputStream(), file.getSize(), -1) //文件流
                .build()
        );

        System.out.println(objectWriteResponse);

        boolean res = userImageService.saveOrUpdateUserImage(id, minIOInfo.getBucket(), object);

        return R.OK(res);
    }

    /**
     * 上传合同
     * @param file 文件
     * @param id id
     */
    @PostMapping(value = "/api/user/contract")
    public R contract(MultipartFile file, @RequestParam(value = "id") Long id) throws Exception {
        //1234.jpg 同uploadImage
        String subFix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().indexOf("."));
        String object = id+subFix;
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder()
                .bucket(minIOInfo.getBucket())
                .object(object)
                .stream(file.getInputStream(), file.getSize(), -1)
                .build()
        );
        System.out.println(objectWriteResponse);
        //更新用户合同记录表
        boolean res = userContractService.saveOrUpdateUserContract(id, minIOInfo.getBucket(), object);
        return R.OK(res);
    }

    /**
     * 查询数据库
     */
    @GetMapping(value = "/api/user/{id}")
    public R user(@PathVariable(value = "id") Integer id) {
        return R.OK(userInfoService.getUserById(id));
    }

    /**
     * 更新用户信息
     */
    @PutMapping(value = "/api/user")
    public R updateUser(UserInfo userInfo) {
        return userInfoService.updateById(userInfo) ? R.OK() : R.FAIL();
    }

    /**
     * 合同文件下载
     * @param id 用户id
     * @param response 返回结果封装
     */
    @GetMapping(value = "/api/download/{id}")
    public void download(@PathVariable(value = "id") Integer id, HttpServletResponse response) throws Exception {

        //查询数据库获取 用户信息 桶信息 和文件对象信息
        UserInfo userInfo = userInfoService.getUserById(id);

        String bucket = userInfo.getUserContractDO().getBucket();
        String object = userInfo.getUserContractDO().getObject();

        //后端设置一下响应头信息，方便浏览器弹出下载框
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(object, StandardCharsets.UTF_8));
        // 从minion获取合同文件数据
        GetObjectResponse getObjectResponse = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucket)
                .object(object)
                .build());

        getObjectResponse.transferTo(response.getOutputStream());
    }

    // 删除用户信息
    @DeleteMapping(value = "/api/user/{id}")
    public R delUser(@PathVariable(value = "id") Integer id) {
        try {
            boolean del = userInfoService.delUserById(id);
            return del ? R.OK() : R.FAIL();
        } catch (Exception e) {
            e.printStackTrace();
            return R.FAIL();
        }
    }

}
